Get Data

  • 1. Step

    Step 1: Create Project (if not already)

    
    
                npm create vite@latest react-api-app -- --template react
                cd react-api-app
                npm install
                npm run dev
    
    
                

    Step 2: Create Component for API Call

    src/components/UserList.jsx

    1. create basic structure
    
    
                import { useEffect, useState } from 'react';
    
    const UserList = () => {
      const [users, setUsers] = useState([]);       // data
     
    
    
    
      return (
        <div>
          <h2>User List</h2>
          <ul>
            {users.map((user) => (
              <li key={user.id}>
                <strong>{user.name}</strong> - {user.email}
              </li>
            ))}
          </ul>
        </div>
      );
    };
    
    export default UserList;
    
    
    
    2. add api call
    
    
                import { useEffect, useState } from 'react';
    
    const UserList = () => {
      const [users, setUsers] = useState([]);       // data
      const [loading, setLoading] = useState(true); // loading state
      const [error, setError] = useState(null);     // error state
    
    
    
    
    
    
      useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
          .then((res) => {
            if (!res.ok) throw new Error('Network error');
            return res.json();
          })
          .then((data) => {
            setUsers(data);
            setLoading(false);
          })
          .catch((err) => {
            setError(err.message);
            setLoading(false);
          });
      }, []);
    
      
    
    
    
      if (loading) return <p>Loading users...</p>;
      if (error) return <p>Error: {error}</p>;
    
      return (
        <div>
          <h2>User List</h2>
          <ul>
            {users.map((user) => (
              <li key={user.id}>
                <strong>{user.name}</strong> - {user.email}
              </li>
            ))}
          </ul>
        </div>
      );
    };
    
    export default UserList;
    
    
    
    fetch() is used to call API

    Step 3: Use It in App.jsx

    
    
    import UserList from './components/UserList';
    
    function App() {
      return (
        <div style={ { padding: '20px' }}>
          <h1>React API Integration</h1>
          <UserList />
        </div>
      );
    }
    
    export default App;